/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package elsimulatorjava;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
/**
 *
 * @author plitter
 */

public class DirectionButton extends JComponent {
    
    private boolean pressed;
    private boolean upButton;
    
    private short floorIndex;
    
    private static Floor[] floors;
    
    private BufferedImage[] button = new BufferedImage[2];
    
    public DirectionButton(Floor[] f, boolean isUpButton) throws IOException {
        floors = f;
        upButton = isUpButton;
        pressed = false;
        if (upButton){
            button[0] = ImageIO.read(new File("images/Button_Up.png"));
            button[1] = ImageIO.read(new File("images/Button_Up_Press.png"));
        } else {
            button[0] = ImageIO.read(new File("images/Button_Down.png"));
            button[1] = ImageIO.read(new File("images/Button_Down_Press.png"));
        }
        setPreferredSize(new Dimension(button[0].getWidth(), button[0].getHeight()));
        addMouseListener(new MouseAdapter() {

            @Override
            public void mouseReleased(MouseEvent me) {
                try {
                    pressed();
                } catch (IOException ex) {
                }
                
            }
        } );
        repaint();
    }
    
    protected void pressed() throws IOException {
        if (upButton){
            floors[floorIndex].setUpButtonOn(true);
        } else {
            floors[floorIndex].setDownButtonOn(true);
        }
        pressed = true;
        repaint();
    }
    
    protected void unpress() throws IOException {
        pressed = false;
        repaint();
    }
    
    protected void setFloorIdx(short fIdx){
        this.floorIndex = fIdx;
    }
    
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        boolean validFloor = false;
        if (upButton){
            if (this.floorIndex != floors.length-1){
                validFloor = true;
            }
        } else {
            if (this.floorIndex != 0){
                validFloor = true;
            }
        }
        if (validFloor){
            if (!pressed){
                g.drawImage(button[0], 0, 0, null);
            } else {
                g.drawImage(button[1], 0, 0, null);
            }
        }
    }
}
